package com.video.demo.service.impl;


import java.math.BigDecimal;
import java.util.Date;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.CreateUploadImageRequest;
import com.aliyuncs.vod.model.v20170321.CreateUploadImageResponse;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoRequest;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoInfoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoInfoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoRequest;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.video.demo.dao.AliyunInfoDao;
import com.video.demo.dto.AliyunImageInfoDto;
import com.video.demo.dto.AliyunVideoInfoDto;
import com.video.demo.entity.VideoInfoEntity;
import com.video.demo.enums.AliyunErrorEnums;
import com.video.demo.service.AliyunInfoService;
import com.video.demo.utils.Constant;
import com.video.demo.utils.DateUtil;

@Service
public class AliyunInfoServiceImpl implements AliyunInfoService {
	@Autowired
	private AliyunInfoDao aliyunInfoDao;
	//@Resource
   // private VideoInfoDao videoInfoDao;
	Logger logger = LoggerFactory.getLogger(AliyunInfoServiceImpl.class);
	private DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", Constant.ACCESS_KEY_ID, Constant.ACCESS_KEY_SECRET);
	private DefaultAcsClient client = new DefaultAcsClient(profile);
	
	/**
	 * 获取播放凭证
	 */
	@Override
	public GetVideoPlayAuthResponse getVideoPlayAuth(String videoId) {
		//获取视频信息
		GetVideoInfoRequest videoInfoRequest = new GetVideoInfoRequest();
		videoInfoRequest.setVideoId(videoId);
		GetVideoInfoResponse videoInfoReponse = null;
		//获取播放信息
		GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
	    request.setVideoId(videoId);
	    GetVideoPlayAuthResponse response = null;
	    try {
	    	videoInfoReponse = client.getAcsResponse(videoInfoRequest);
	    	if(AliyunErrorEnums.TRANSCODE_FAIL.getErrorCode().equals(videoInfoReponse.getVideo().getStatus())){
	    		logger.info("视频信息："+videoInfoReponse.getVideo().toString());
	    		throw new RuntimeException(AliyunErrorEnums.TRANSCODE_FAIL.getErrorMessage());
	    	}else if(AliyunErrorEnums.TRANSCODING.getErrorCode().equals(videoInfoReponse.getVideo().getStatus())){
	    		logger.info("视频信息："+videoInfoReponse.getVideo().toString());
	    		throw new RuntimeException(AliyunErrorEnums.TRANSCODING.getErrorMessage());
	    	}
	        response = client.getAcsResponse(request);
	    } catch (ServerException e) {
	        throw new RuntimeException(AliyunErrorEnums.getMsgByCode(e.getErrCode()));
	    } catch (ClientException e) {
	        throw new RuntimeException(AliyunErrorEnums.getMsgByCode(e.getErrCode()));
	    }
	    response.getPlayAuth();              //播放凭证
	    response.getVideoMeta();             //视频Meta信息
	    return response;
	}
	
	/**
	 * 获取上传地址和凭证
	 */
	@Override
	public AliyunVideoInfoDto getVideoUploadInfo(String fileName,String title,String coverURL,Integer cateId,String tags,String description,Long fileSize) {
		AliyunVideoInfoDto uploadVideoDto = new AliyunVideoInfoDto();
		
		CreateUploadVideoRequest request = new CreateUploadVideoRequest();
        CreateUploadVideoResponse response = null;
        try {
              request.setFileName(fileName);
              //必选，视频标题
              request.setTitle(title);
              //可选，自定义视频封面URL地址
              request.setCoverURL(coverURL);
              //可选，分类ID
              request.setCateId(cateId);
              //可选，视频标签，多个用逗号分隔
              request.setTags(tags);
              //可选，视频描述
              request.setDescription(description);
              //可选，视频源文件字节数
              request.setFileSize(fileSize);
              response = client.getAcsResponse(request);
        } catch (ServerException e) {
              throw new RuntimeException(AliyunErrorEnums.getMsgByCode(e.getErrCode()));
        } catch (ClientException e) {
              throw new RuntimeException(AliyunErrorEnums.getMsgByCode(e.getErrCode()));
        }
        logger.info("视频RequestId:"+response.getRequestId());
        logger.info("视频UploadAuth:"+response.getUploadAuth());
        logger.info("视频UploadAddress:"+response.getUploadAddress());
        uploadVideoDto.setRequestId(response.getRequestId());
        uploadVideoDto.setVideoId(response.getVideoId());
        uploadVideoDto.setUploadAddress(response.getUploadAddress());
        uploadVideoDto.setUploadAuth(response.getUploadAuth());
		
		//当网络异常导致文件上传失败时,可刷新上传凭证后再次执行上传操作
		//refreshUploadAtuh(uploadVideoDto.getVideoId());
		return uploadVideoDto;
	}

	/**
	 * 刷新视频上传凭证
	 */
	@Override
	public String refreshVideoUploadAtuh(String videoId) {
		RefreshUploadVideoRequest request = new RefreshUploadVideoRequest();
        RefreshUploadVideoResponse response = null;
        try {
              request.setVideoId(videoId);
              response = client.getAcsResponse(request);
        } catch (ServerException e) {
              throw new RuntimeException(AliyunErrorEnums.getMsgByCode(e.getErrCode()));
        } catch (ClientException e) {
              throw new RuntimeException(AliyunErrorEnums.getMsgByCode(e.getErrCode()));
        }
        logger.info("视频RequestId:" + response.getRequestId());
        logger.info("视频UploadAuth:" + response.getUploadAuth());
        return response.getUploadAuth();
	}


	/**
	 * 获取图片上传地址和凭证
	 */
	@Override
	public AliyunImageInfoDto getImageUploadInfo(String imageType,
			String imageExt) {
		AliyunImageInfoDto imageInfoDto = new AliyunImageInfoDto();
		CreateUploadImageRequest request = new CreateUploadImageRequest();
		CreateUploadImageResponse response = null;
        try {
              request.setImageType(imageType);
              request.setImageExt(imageExt);
              
              response = client.getAcsResponse(request);
        } catch (ServerException e) {
              throw new RuntimeException(AliyunErrorEnums.getMsgByCode(e.getErrCode()));
        } catch (ClientException e) {
              throw new RuntimeException(AliyunErrorEnums.getMsgByCode(e.getErrCode()));
        }
        logger.info("图片RequestId:"+response.getRequestId());
        logger.info("图片UploadAuth:"+response.getUploadAuth());
        logger.info("图片UploadAddress:"+response.getUploadAddress());
        logger.info("图片ImageUrl:"+response.getImageURL());
        imageInfoDto.setRequestId(response.getRequestId());
        imageInfoDto.setUploadAddress(response.getUploadAddress());
        imageInfoDto.setUploadAuth(response.getUploadAuth());
        imageInfoDto.setImageUrl(response.getImageURL());
		return imageInfoDto;
	}
	/**
	 * 更新视频
	 */
	@Override
	public void transcodeComplete(String status, String aliyunVideoId,
			String duration, String fileUrl) {
		try {
			//解码成功
			if("success".equals(status)){
				BigDecimal decimal = new BigDecimal(duration).setScale(0, BigDecimal.ROUND_HALF_UP);
				//转换成00:00或者00:00:00格式
				String str = DateUtil.toMinuteSecond(Long.valueOf(decimal.toString()));
				if(str.length()==5){
					str = "00:"+str;
				}
				//转成日期
				Date time = DateUtil.stringToDate(str,"HH:mm:ss.SSS");
				logger.info("转换后的time:"+time);
				VideoInfoEntity entity = null;
				//根据aliyunVideoId判断是否有数据，有则更新，无则插入
				//entity = videoInfoDao.getVideoByAliyunId(aliyunVideoId);
				if(entity!=null){
					aliyunInfoDao.updateVideoInfo(time, fileUrl, aliyunVideoId);
				}else{
					entity= new VideoInfoEntity(Constant.idWorker.nextId(),fileUrl, time,aliyunVideoId);
					//videoInfoDao.insert(entity);
				}
			}
		} catch (Exception e) {
			logger.error("更新视频失败",e);
		}
	}}
